package mqtt

import (
	"log"
	"strconv"
	"time"

	tpprotocolsdkgo "github.com/ThingsPanel/tp-protocol-sdk-go"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var MqttClient *tpprotocolsdkgo.MQTTClient

func InitClient() {
	logrus.Info("创建mqtt客户端")
	// 创建新的MQTT客户端实例
	addr := viper.GetString("mqtt.broker")
	var username, password string
	if viper.GetString("version") == "new" {
		username = viper.GetString("mqtt.username")
		password = viper.GetString("mqtt.password")
	} else {
		username = viper.GetString("mqtt.username_old")
		password = viper.GetString("mqtt.password_old")
	}
	client := tpprotocolsdkgo.NewMQTTClient(addr, username, password)
	// 尝试连接到MQTT代理
	if err := client.Connect(); err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	logrus.Info("连接成功")
	MqttClient = client
}

// 发布遥测消息
func Publish(payload string) error {
	// 主题
	topic := viper.GetString("mqtt.topic_to_publish")
	qos := viper.GetUint("mqtt.qos")
	// 发布消息
	if err := MqttClient.Publish(topic, string(payload), uint8(qos)); err != nil {
		log.Printf("发布消息失败: %v", err)
		return err
	}
	logrus.Debug("主题:", topic)
	logrus.Debug("\ni====>tp:", payload)
	return nil
}

// 发布属性到平台
func PublishAttributes(device string, payload []byte) error {
	var topic string
	if viper.GetString("version") == "new" {
		topic = viper.GetString("mqtt.topic_to_publish_attributes") + GetMessageID()
	} else {
		topic = viper.GetString("mqtt.topic_to_publish_attributes_old")
	}
	qos := viper.GetUint("mqtt.qos")
	// 发布消息
	if err := MqttClient.Publish(topic, string(payload), uint8(qos)); err != nil {
		log.Printf("发布消息失败: %v", err)
		return err
	}
	logrus.Debug("设备主题:", topic)
	logrus.Debug("\n==>tp 发送消息成功:", string(payload))
	return nil
}

// 发布事件到平台
func PublishEvent(device string, payload []byte) error {
	topic := viper.GetString("mqtt.topic_to_publish_event") + GetMessageID()
	qos := viper.GetUint("mqtt.qos")
	// 发布消息
	if err := MqttClient.Publish(topic, string(payload), uint8(qos)); err != nil {
		log.Printf("发布消息失败: %v", err)
		return err
	}
	logrus.Debug("设备主题:", topic)
	logrus.Debug("\n==>tp 发送消息成功:", string(payload))
	return nil
}

func GetMessageID() string {
	// 获取当前Unix时间戳
	timestamp := time.Now().Unix()
	// 将时间戳转换为字符串
	timestampStr := strconv.FormatInt(timestamp, 10)
	// 截取后七位
	messageID := timestampStr[len(timestampStr)-7:]

	return messageID
}
